package com.ruoyi.common.utils.rabbitmq;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author xudengyu
 */
@Component
@Slf4j
public class RabbitMQProducerService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private DirectExchange directExchange;

    @Resource
    private RabbitMQConsumerService rabbitMQConsumerService;

    public boolean isQueueExists(String queueName) {
        RabbitAdmin admin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());
        return admin.getQueueProperties(queueName) != null;
    }

    public void createAndBindQueue(String queueName, String routingKey, String userId) {
//        rabbitMQConsumerService.addQueueListener(queueName, userId);
        if (isQueueExists(queueName)) return; // 队列已存在则跳过

        Queue queue = new Queue(queueName, true, false, false);
        Binding binding = BindingBuilder.bind(queue)
                .to(directExchange)
                .with(RabbitMQDynamicConfig.ROUTING_KEY_PREFIX + routingKey);
        AmqpAdmin amqpAdmin = new RabbitAdmin(rabbitTemplate.getConnectionFactory());
        amqpAdmin.declareQueue(queue);
        amqpAdmin.declareBinding(binding);
    }

    public void sendMessage(String key, String message) {
        String messageId = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(messageId);

        try {
            RabbitMQUtil.sendMessage(
                    rabbitTemplate,
                    RabbitMQDynamicConfig.EXCHANGE_NAME,
                    key,
                    message,
                    correlationData
            );
            log.info("## 发送消息：{}",key);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("消息发送被中断: " + e.getMessage());
        }
    }
}
